package MyRedis

import (
	"regexp"
	"time"
)

type CachePolicy interface {
	Before(key string)                       //过滤缓存key
	IfNil(key string, val interface{})       //数据不存在时 设置空缓存
	SetOperation(operation *StringOperation) //缓存操作类  暂时主要用于IfNil
}

type CrossPolicy struct {
	keyRegx string           //正则
	Expire  time.Duration    //过期时间
	opt     *StringOperation //缓存操作类
}

func NewCrossPolicy(keyRegx string, exp time.Duration) *CrossPolicy {
	return &CrossPolicy{
		keyRegx: keyRegx,
		Expire:  exp,
	}
}

/**
Before 中间件 过滤不符合要求的key
*/
func (c *CrossPolicy) Before(key string) {
	if !regexp.MustCompile(c.keyRegx).MatchString(key) {
		panic("err cache key")
	}
}

/**
IfNil 设置空缓存
*/
func (c *CrossPolicy) IfNil(key string, val interface{}) {
	c.opt.Set(key, val, WithExpire(c.Expire)).Unwrap()
}

/**
SetOperation 设置缓存操作类用于IfNil操作
*/
func (c *CrossPolicy) SetOperation(opt *StringOperation) {
	c.opt = opt
}
